import Vue from 'vue'
import VueRouter from 'vue-router'
import { Dialog } from 'vant'
import store from '@/store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: () => import(/* webpackChunkName: "Login" */ '@/views/Login')
  },
  {
    path: '/',
    component: () => import(/* webpackChunkName: "Layout" */ '@/views/Layout'),
    children: [
      {
        path: '',
        name: 'home',
        component: () => import(/* webpackChunkName: "Home" */ '@/views/Home')
      },
      {
        path: '/qa',
        name: 'qa',
        component: () => import(/* webpackChunkName: "Qa" */ '@/views/Qa')
      },
      {
        path: '/video',
        name: 'video',
        component: () => import(/* webpackChunkName: "Video" */ '@/views/Video')
      },
      {
        path: '/my',
        name: 'my',
        component: () => import(/* webpackChunkName: "My" */ '@/views/My')
      }
    ]
  },
  {
    path: '/search',
    name: 'search',
    component: () => import(/* webpackChunkName: "Search" */ '@/views/Search')
  },
  {
    path: '/article/:articleId',
    name: 'article',
    component: () => import(/* webpackChunkName: "Article" */ '@/views/Article'),
    props: true
  },
  {
    path: '/user/profile',
    name: 'user-profile',
    component: () => import(/* webpackChunkName: "UserProfile" */ '@/views/UserProfile')

  },
  {
    path: '/user/chat',
    name: 'user-chat',
    component: () => import(/* webpackChunkName: "UserChat" */ '@/views/UserChat'),
    meta: { requiresAuth: true }
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth) {
    if (store.state.userToken) {
      return next()
    }
    Dialog.confirm({
      title: '访问提示',
      message: '该功能需要登录才能访问，确认需要登录吗'
    }).then(() => {
      router.replace({
        path: '/login',
        query: {
          redireact: router.currentRoute.fullPath
        }
      })
    }).catch(() => {
      next(false)
    })
  } else {
    next() // 确保一定要调用 next()
  }
})

export default router
